#include <iostream>
#include <vector>
#include <queue>
#include <map>
#include <utility>
#include <string>
using namespace std;

class Solution {
public:
    typedef pair<int, int> pii;

    int dx[4] = { 0, 0, 1, -1 };
    int dy[4] = { 1, -1, 0, 0 };

    int nearestExit(vector<vector<char>>& maze, vector<int>& entrance)
    {
        int step = 0, row = maze.size(), col = maze[0].size();

        vector<vector<bool>> vv(row, vector<bool>(col, true)); vv[entrance[0]][entrance[1]] = false;
        queue<pii> q; q.emplace(entrance[0], entrance[1]);

        while (q.size())
        {
            int num = q.size();
            step++;

            for (int k = 0; k < num; k++)
            {
                auto [a, b] = q.front(); q.pop();

                for (int i = 0; i < 4; i++)
                {
                    int x = a + dx[i];
                    int y = b + dy[i];

                    if (x >= 0 && x < row && y >= 0 && y < col && maze[x][y] != '+' && vv[x][y] == true)
                    {
                        if (x == 0 || y == 0 || x == row - 1 || y == col - 1) return step;
                        else
                        {
                            vv[x][y] = false;
                            q.emplace(x, y);
                        }
                    }
                }
            }

        }

        return -1;
    }
};


int main()
{
    vector<vector<char>> vv{ {'+','.','+','+','+','+','+'},
                         {'+','.','+','.','.','.','+'},
                         {'+','.','+','.','+','.','+'},
                         {'+','.','.','.','+','.','+'},
                         {'+','+','+','+','+','.','+'} };

    vector<int> v{ 0,1 };

    Solution a;
    cout << a.nearestExit(vv, v);

    return 0;
}